package com.evaluation.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.evaluation.common.Result;
import com.evaluation.entity.Indicators;
import com.evaluation.entity.IndicatorsPoints;
import com.evaluation.service.IndicatorsPointsService;
import com.evaluation.service.IndicatorsService;
import com.evaluation.util.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 考核指标管理控制器
 */
@RestController
@RequestMapping("/api/admin/indicators")
public class AdminIndicatorsController {

    @Autowired
    private IndicatorsService indicatorsService;

    @Autowired
    private IndicatorsPointsService indicatorsPointsService;

    /**
     * 获取所有考核指标（无分页）
     */
    @GetMapping("")
    public Result getAllIndicators() {
        try {
            List<Indicators> list = indicatorsService.list();
            return Result.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取考核指标列表失败");
        }
    }

    /**
     * 分页查询考核指标列表
     */
    @GetMapping("/list")
    public Result getIndicatorsList(@RequestParam(defaultValue = "1") Integer page,
                                    @RequestParam(defaultValue = "10") Integer size,
                                    @RequestParam(required = false) String zbmc,
                                    @RequestParam(required = false) String khfs) {
        try {
            QueryWrapper<Indicators> queryWrapper = new QueryWrapper<>();

            if (zbmc != null && !zbmc.trim().isEmpty()) {
                queryWrapper.like("ZBMC", zbmc);
            }

            if (khfs != null && !khfs.trim().isEmpty()) {
                queryWrapper.eq("KHFS", khfs);
            }

            queryWrapper.orderByAsc("PX", "ZBBH");

            Page<Indicators> pageResult = indicatorsService.page(new Page<>(page, size), queryWrapper);

            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询考核指标列表失败");
        }
    }

    /**
     * 获取所有考核指标（用于下拉选择）
     */
    @GetMapping("/options")
    public Result getIndicatorsOptions() {
        try {
            QueryWrapper<Indicators> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByAsc("PX", "ZBBH");
            queryWrapper.select("ZBBH", "ZBMC", "KHFS");

            List<Indicators> indicatorsList = indicatorsService.list(queryWrapper);
            return Result.success(indicatorsList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取考核指标选项失败");
        }
    }

    /**
     * 根据ID查询考核指标详情
     */
    @GetMapping("/{zbbh}")
    public Result getIndicatorById(@PathVariable String zbbh) {
        try {
            Indicators indicator = indicatorsService.getById(zbbh);
            if (indicator == null) {
                return Result.error("考核指标不存在");
            }
            return Result.success(indicator);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询考核指标详情失败");
        }
    }

    /**
     * 新增考核指标
     */
    @PostMapping
    public Result addIndicator(@RequestBody Indicators indicator) {
        try {
            // 验证必填字段
            if (indicator.getZbbh() == null || indicator.getZbbh().trim().isEmpty()) {
                return Result.error("指标编号不能为空");
            }
            
            if (indicator.getZbmc() == null || indicator.getZbmc().trim().isEmpty()) {
                return Result.error("指标名称不能为空");
            }
            
            // 检查指标编号是否已存在
            Indicators existingIndicator = indicatorsService.getById(indicator.getZbbh().trim());
            if (existingIndicator != null) {
                return Result.error("指标编号已存在");
            }
            
            // 检查指标名称是否已存在
            QueryWrapper<Indicators> nameQueryWrapper = new QueryWrapper<>();
            nameQueryWrapper.eq("ZBMC", indicator.getZbmc().trim());
            Indicators existingByName = indicatorsService.getOne(nameQueryWrapper);
            if (existingByName != null) {
                return Result.error("指标名称已存在");
            }
            
            // 设置字段值
            indicator.setZbbh(indicator.getZbbh().trim());
            indicator.setZbmc(indicator.getZbmc().trim());
            
            // 设置默认排序
            if (indicator.getPx() == null || indicator.getPx().trim().isEmpty()) {
                indicator.setPx("1");
            }

            boolean result = indicatorsService.save(indicator);
            if (result) {
                return Result.success("添加成功");
            } else {
                return Result.error("添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("添加考核指标失败：" + e.getMessage());
        }
    }

    /**
     * 更新考核指标
     */
    @PutMapping("/{zbbh}")
    public Result updateIndicator(@PathVariable String zbbh, @RequestBody Indicators indicator) {
        try {
            indicator.setZbbh(zbbh);
            boolean result = indicatorsService.updateById(indicator);
            if (result) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新考核指标失败");
        }
    }

    /**
     * 删除考核指标
     */
    @DeleteMapping("/{zbbh}")
    public Result deleteIndicator(@PathVariable String zbbh) {
        try {
            boolean result = indicatorsService.removeById(zbbh);
            if (result) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除考核指标失败");
        }
    }

    /**
     * 批量导入考核指标
     */
    @PostMapping("/import")
    public Result importIndicators(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.error("上传文件不能为空");
            }

            // 读取Excel文件
            List<Map<String, Object>> dataList = ExcelUtil.readExcel(file);
            
            int successCount = 0;
            int errorCount = 0;

            for (Map<String, Object> data : dataList) {
                try {
                    // 验证必填字段
                    if (data.get("考核指标编号") == null || data.get("考核指标名称") == null) {
                        errorCount++;
                        continue;
                    }

                    Indicators indicator = new Indicators();
                    indicator.setZbbh(String.valueOf(data.get("考核指标编号")));
                    indicator.setZbmc(String.valueOf(data.get("考核指标名称")));
                    
                    // 设置排序，默认为1
                    if (data.get("排序") != null) {
                        indicator.setPx(String.valueOf(data.get("排序")));
                    } else {
                        indicator.setPx("1");
                    }
                    
                    // 设置考核方式，默认为0
                    if (data.get("考核方式") != null) {
                        indicator.setKhfs(String.valueOf(data.get("考核方式")));
                    } else {
                        indicator.setKhfs("0");
                    }

                    // 检查指标编号是否已存在
                    Indicators existingIndicator = indicatorsService.getById(indicator.getZbbh());
                    if (existingIndicator == null) {
                        indicatorsService.save(indicator);
                        successCount++;
                    } else {
                        // 更新现有指标
                        indicatorsService.updateById(indicator);
                        successCount++;
                    }
                } catch (Exception e) {
                    errorCount++;
                }
            }

            return Result.success("导入完成，成功：" + successCount + "条，失败：" + errorCount + "条");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("导入考核指标失败");
        }
    }

    // ========== 考核点管理 ==========

    /**
     * 分页查询考核点列表
     */
    @GetMapping("/points/list")
    public Result getIndicatorPointsList(@RequestParam(defaultValue = "1") Integer page,
                                         @RequestParam(defaultValue = "10") Integer size,
                                         @RequestParam(required = false) String zbbh,
                                         @RequestParam(required = false) String khdmc) {
        try {
            QueryWrapper<IndicatorsPoints> queryWrapper = new QueryWrapper<>();

            if (zbbh != null && !zbbh.trim().isEmpty()) {
                queryWrapper.eq("ZBBH", zbbh);
            }

            if (khdmc != null && !khdmc.trim().isEmpty()) {
                queryWrapper.like("KHDMC", khdmc);
            }

            queryWrapper.orderByAsc("ZBBH", "KHDBH");

            Page<IndicatorsPoints> pageResult = indicatorsPointsService.page(new Page<>(page, size), queryWrapper);

            // 批量查询指标信息，组装指标名称
            List<IndicatorsPoints> records = pageResult.getRecords();
            if (records != null && !records.isEmpty()) {
                // 收集所有指标编号
                List<String> zbbhList = records.stream()
                        .map(IndicatorsPoints::getZbbh)
                        .distinct()
                        .collect(Collectors.toList());
                
                // 批量查询指标信息
                List<Indicators> indicatorsList = indicatorsService.listByIds(zbbhList);
                Map<String, String> zbbhToZbmcMap = new HashMap<>();
                if (indicatorsList != null) {
                    for (Indicators indicator : indicatorsList) {
                        zbbhToZbmcMap.put(indicator.getZbbh(), indicator.getZbmc());
                    }
                }
                
                // 为每个考核点添加指标名称（使用Map临时存储）
                List<Map<String, Object>> resultList = new ArrayList<>();
                for (IndicatorsPoints point : records) {
                    Map<String, Object> pointMap = new HashMap<>();
                    pointMap.put("zbbh", point.getZbbh());
                    pointMap.put("zbmc", zbbhToZbmcMap.getOrDefault(point.getZbbh(), ""));
                    pointMap.put("khdbh", point.getKhdbh());
                    pointMap.put("khdmc", point.getKhdmc());
                    pointMap.put("khdqz", point.getKhdqz());
                    pointMap.put("khdxj", point.getKhdxj());
                    pointMap.put("a", point.getA());
                    pointMap.put("b", point.getB());
                    pointMap.put("c", point.getC());
                    pointMap.put("d", point.getD());
                    pointMap.put("e", point.getE());
                    resultList.add(pointMap);
                }
                
                // 创建新的分页结果
                Page<Map<String, Object>> resultPage = new Page<>(pageResult.getCurrent(), pageResult.getSize(), pageResult.getTotal());
                resultPage.setRecords(resultList);
                return Result.success(resultPage);
            }

            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询考核点列表失败");
        }
    }

    /**
     * 根据指标编号查询考核点
     */
    @GetMapping("/{zbbh}/points")
    public Result getPointsByIndicator(@PathVariable String zbbh) {
        try {
            QueryWrapper<IndicatorsPoints> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("ZBBH", zbbh);
            queryWrapper.orderByAsc("KHDBH");

            List<IndicatorsPoints> pointsList = indicatorsPointsService.list(queryWrapper);
            return Result.success(pointsList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询考核点失败");
        }
    }

    /**
     * 根据指标编号和考核点编号查询考核点详情
     */
    @GetMapping("/points/{zbbh}/{khdbh}")
    public Result getIndicatorPointDetail(@PathVariable String zbbh, @PathVariable String khdbh) {
        try {
            QueryWrapper<IndicatorsPoints> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("ZBBH", zbbh);
            queryWrapper.eq("KHDBH", khdbh);

            IndicatorsPoints point = indicatorsPointsService.getOne(queryWrapper);
            if (point == null) {
                return Result.error("考核点不存在");
            }
            return Result.success(point);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询考核点详情失败");
        }
    }

    /**
     * 新增考核点
     */
    @PostMapping("/points")
    public Result addIndicatorPoint(@RequestBody IndicatorsPoints point) {
        try {
            boolean result = indicatorsPointsService.save(point);
            if (result) {
                return Result.success("添加成功");
            } else {
                return Result.error("添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("添加考核点失败");
        }
    }

    /**
     * 更新考核点
     */
    @PutMapping("/points/{zbbh}/{khdbh}")
    public Result updateIndicatorPoint(@PathVariable String zbbh,
                                       @PathVariable String khdbh,
                                       @RequestBody IndicatorsPoints point) {
        try {
            // 设置复合主键
            point.setZbbh(zbbh);
            point.setKhdbh(khdbh);

            // 使用条件更新，因为是联合主键
            QueryWrapper<IndicatorsPoints> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("ZBBH", zbbh);
            queryWrapper.eq("KHDBH", khdbh);

            boolean result = indicatorsPointsService.update(point, queryWrapper);
            if (result) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新考核点失败");
        }
    }

    /**
     * 删除考核点
     */
    @DeleteMapping("/points/{zbbh}/{khdbh}")
    public Result deleteIndicatorPoint(@PathVariable String zbbh, @PathVariable String khdbh) {
        try {
            // 使用复合主键删除
            QueryWrapper<IndicatorsPoints> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("ZBBH", zbbh);
            queryWrapper.eq("KHDBH", khdbh);

            boolean result = indicatorsPointsService.remove(queryWrapper);
            if (result) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除考核点失败");
        }
    }

    /**
     * 批量导入考核点
     */
    @PostMapping("/points/import")
    public Result importIndicatorPoints(@RequestBody List<IndicatorsPoints> pointsList) {
        try {
            int successCount = 0;
            int errorCount = 0;

            for (IndicatorsPoints point : pointsList) {
                try {
                    indicatorsPointsService.save(point);
                    successCount++;
                } catch (Exception e) {
                    errorCount++;
                }
            }

            return Result.success("导入完成，成功：" + successCount + "条，失败：" + errorCount + "条");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("导入考核点失败");
        }
    }

    /**
     * 获取所有考核点（无分页）
     */
    @GetMapping("/points")
    public Result getAllIndicatorPoints() {
        try {
            List<IndicatorsPoints> list = indicatorsPointsService.list();
            return Result.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取考核点列表失败");
        }
    }

    /**
     * 下载考核点导入模板
     */
    @GetMapping("/indicator-points/template/download")
    public void downloadIndicatorPointsTemplate(HttpServletResponse response) {
        try {
            // 创建模板数据
            List<Map<String, Object>> templateData = new ArrayList<>();
            
            // 添加示例数据
            Map<String, Object> example1 = new HashMap<>();
            example1.put("考核指标编号", "11");
            example1.put("考核点编号", "1");
            example1.put("考核点名称", "品德品质(20分)-11");
            example1.put("考核点权重", "0.2");
            example1.put("考核点详解", "政治素养:坚定理想信念，明确政治方向，坚决贯彻上级决策部署。品德修养:品格高尚，表里如一，为人师表，全心全意，服务师生。师德师风:遵守原则，责任意识强，敢于担当，敢抓敢管。");
            example1.put("A等分值", "20");
            example1.put("B等分值", "18");
            example1.put("C等分值", "15");
            example1.put("D等分值", "12");
            example1.put("E等分值", "10");
            templateData.add(example1);

            Map<String, Object> example2 = new HashMap<>();
            example2.put("考核指标编号", "11");
            example2.put("考核点编号", "2");
            example2.put("考核点名称", "教学能力(30分)-11");
            example2.put("考核点权重", "0.3");
            example2.put("考核点详解", "专业素养:注重院系专业发展规划，关注专业人才培养质量，重视专业师资队伍、实训基地、课程等建设。品牌建设:注重品牌建设，团队在各类专业(群)、课程、实训基地、团队、教改等方面获得省级以上各类项目、奖励。交流合作:团队积极参与学院对外交流合作，积极组织对外交流活动，总结推广成果，应用于教学实践。");
            example2.put("A等分值", "30");
            example2.put("B等分值", "27");
            example2.put("C等分值", "23");
            example2.put("D等分值", "18");
            example2.put("E等分值", "15");
            templateData.add(example2);

            Map<String, Object> example3 = new HashMap<>();
            example3.put("考核指标编号", "21");
            example3.put("考核点编号", "1");
            example3.put("考核点名称", "教学实践(30分)-21");
            example3.put("考核点权重", "0.3");
            example3.put("考核点详解", "教学实践能力考核，包括课堂教学、实践指导、学生管理等方面的综合表现。");
            example3.put("A等分值", "30");
            example3.put("B等分值", "27");
            example3.put("C等分值", "23");
            example3.put("D等分值", "18");
            example3.put("E等分值", "15");
            templateData.add(example3);
            
            // 导出Excel
            ExcelUtil.exportExcel(response, "考核点导入模板", templateData);
            
        } catch (Exception e) {
            e.printStackTrace();
            // 如果导出失败，返回错误信息
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 下载考核指标导入模板
     */
    @GetMapping("/template/download")
    public void downloadIndicatorsTemplate(HttpServletResponse response) {
        try {
            // 创建模板数据
            List<Map<String, Object>> templateData = new ArrayList<>();
            
            // 添加示例数据
            Map<String, Object> example1 = new HashMap<>();
            example1.put("考核指标编号", "11");
            example1.put("考核指标名称", "校领导");
            example1.put("排序", "1");
            example1.put("考核方式", "0");
            templateData.add(example1);

            Map<String, Object> example2 = new HashMap<>();
            example2.put("考核指标编号", "12");
            example2.put("考核指标名称", "专业干部");
            example2.put("排序", "2");
            example2.put("考核方式", "0");
            templateData.add(example2);

            Map<String, Object> example3 = new HashMap<>();
            example3.put("考核指标编号", "21");
            example3.put("考核指标名称", "教学实践");
            example3.put("排序", "7");
            example3.put("考核方式", "1");
            templateData.add(example3);
            
            // 导出Excel
            ExcelUtil.exportExcel(response, "考核指标导入模板", templateData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入考核点数据
     */
    @PostMapping("/indicator-points/import")
    public Result importIndicatorPoints(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.error("上传文件不能为空");
            }

            // 读取Excel文件
            List<Map<String, Object>> dataList = ExcelUtil.readExcel(file);
            
            if (dataList.isEmpty()) {
                return Result.error("Excel文件中没有有效数据");
            }

            int successCount = 0;
            int errorCount = 0;

            for (Map<String, Object> data : dataList) {
                try {
                    // 验证必填字段
                    if (data.get("考核指标编号") == null || data.get("考核点编号") == null || 
                        data.get("考核点名称") == null) {
                        errorCount++;
                        continue;
                    }

                    IndicatorsPoints point = new IndicatorsPoints();
                    point.setZbbh(String.valueOf(data.get("考核指标编号")));
                    point.setKhdbh(String.valueOf(data.get("考核点编号")));
                    point.setKhdmc(String.valueOf(data.get("考核点名称")));
                    
                    // 设置考核点权重，默认为0.25
                    if (data.get("考核点权重") != null) {
                        point.setKhdqz(Double.valueOf(String.valueOf(data.get("考核点权重"))));
                    } else {
                        point.setKhdqz(0.25);
                    }
                    
                    // 设置考核点详解
                    if (data.get("考核点详解") != null) {
                        point.setKhdxj(String.valueOf(data.get("考核点详解")));
                    }
                    
                    // 设置各等级分值
                    if (data.get("A等分值") != null) {
                        point.setA(Integer.valueOf(String.valueOf(data.get("A等分值"))));
                    }
                    if (data.get("B等分值") != null) {
                        point.setB(Integer.valueOf(String.valueOf(data.get("B等分值"))));
                    }
                    if (data.get("C等分值") != null) {
                        point.setC(Integer.valueOf(String.valueOf(data.get("C等分值"))));
                    }
                    if (data.get("D等分值") != null) {
                        point.setD(Integer.valueOf(String.valueOf(data.get("D等分值"))));
                    }
                    if (data.get("E等分值") != null) {
                        point.setE(Integer.valueOf(String.valueOf(data.get("E等分值"))));
                    }

                    // 检查是否已存在相同的考核点
                    QueryWrapper<IndicatorsPoints> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("ZBBH", point.getZbbh());
                    queryWrapper.eq("KHDBH", point.getKhdbh());

                    IndicatorsPoints existingPoint = indicatorsPointsService.getOne(queryWrapper);
                    if (existingPoint == null) {
                        indicatorsPointsService.save(point);
                        successCount++;
                    } else {
                        // 更新现有考核点
                        if (point.getKhdmc() != null) existingPoint.setKhdmc(point.getKhdmc());
                        if (point.getKhdqz() != null) existingPoint.setKhdqz(point.getKhdqz());
                        if (point.getKhdxj() != null) existingPoint.setKhdxj(point.getKhdxj());
                        if (point.getA() != null) existingPoint.setA(point.getA());
                        if (point.getB() != null) existingPoint.setB(point.getB());
                        if (point.getC() != null) existingPoint.setC(point.getC());
                        if (point.getD() != null) existingPoint.setD(point.getD());
                        if (point.getE() != null) existingPoint.setE(point.getE());
                        
                        indicatorsPointsService.updateById(existingPoint);
                        successCount++;
                    }
                } catch (Exception e) {
                    errorCount++;
                    e.printStackTrace();
                }
            }

            return Result.success("导入完成，成功：" + successCount + "条，失败：" + errorCount + "条");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("导入考核点失败：" + e.getMessage());
        }
    }

}
